import { useState, useRef, useEffect } from 'react';
import { Form, Input, message } from 'antd';
import styles from './index.less';
import classNames from 'classnames';
import CheckTag from '../../components/CheckTag';
import { DraggerUpload } from '@/pages/pc/components/Upload';
import { useForm } from 'antd/lib/form/Form';
import { allGet } from '@/services/pc';
import { isVideo } from '@/utils';
import VideoPlayerModal from '../../components/VideoPlayer';
import regMap from '@/utils/regMap';
import { history } from 'umi';
import { apiUrl } from '@/common/const';

interface ContactProps {
  onChange?: (value: any[]) => void;
}
const Contact: React.FC<ContactProps> = ({ onChange }) => {
  const [fileds, setFileds] = useState([
    { key: 'mobiles', name: '手机号', checked: false, value: '' },
    { key: 'qq', name: 'QQ号', checked: false, value: '' },
    { key: 'weixin', name: '微信号', checked: false, value: '' },
  ]);

  const handleClick = (index) => {
    const newFileds = [...fileds];
    newFileds[index].checked = !newFileds[index].checked;
    setFileds(newFileds);
    onChange?.(newFileds);
  };
  const handleBlur = (value, index) => {
    const newFileds = [...fileds];
    newFileds[index].value = value;
    setFileds(newFileds);
    onChange?.(newFileds);
  };
  return (
    <div className={styles.contact}>
      {fileds.map((item, index) => (
        <div key={item.key} className={styles.item}>
          <i
            className={classNames(styles.icon, { [styles.checked]: item.checked })}
            onClick={() => handleClick(index)}
          />
          <div className={styles.wrapper}>
            <div className={styles.key}>{item.name}</div>
            <input
              className={styles.value}
              type="text"
              onBlur={(e) => handleBlur(e.target.value, index)}
            />
          </div>
        </div>
      ))}
    </div>
  );
};

const Gender = ({ onChange, value }: any) => {
  const handleClick = (value) => {
    onChange?.(value);
  };
  return (
    <div className={styles.gender}>
      <div
        className={classNames(styles.item, styles.male, { [styles.actived]: value === 1 })}
        onClick={() => handleClick(1)}
      />
      <div
        className={classNames(styles.item, styles.female, { [styles.actived]: value === 2 })}
        onClick={() => handleClick(2)}
      />
    </div>
  );
};

const getAliyunAuth = async (data = {} as any) => {
  // let createUrl = '/api2/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6'
  // const reponse = await request.get(createUrl)
  // return reponse;
  const response = await allGet({
    params: {
      mod: 'video',
      do: 'aliyun',
      version: 'pc1.0',
      action: 'CreateUploadVideo',
      CateId: '1000422147',
      ...data,
    },
  });
  return response?.data || {};
};

const refreshAliyunAuth = async (data = {}) => {
  // let refreshUrl = '/api2/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + data.VideoId

  // const reponse = await request.get(refreshUrl)
  // return reponse

  const response = await allGet({
    params: { mod: 'video', do: 'aliyun', version: 'pc1.0', action: 'RefreshUploadVideo', ...data },
  });
  return response?.data || {};
};
const ApplyForm = ({ config, onSubmit, loading }) => {
  const categorys =
    config?.data?.categorys?.map((item) => ({ label: item.name, value: item.cid })) || [];

  const uploadPayload = {
    mod: 'swfupload',
    ac: 'teacher',
    field: 'project',
    version: 'pc1.0',
    uid: config?.data?.space?.uid,
    hash: config?.data?.swfconfig?.hash,
  };
  const [form] = useForm();

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      onSubmit(values);
    } catch (error) {}
  };

  const validUpload = (rule, value: any) => {
    if (!value) return Promise.reject('请上传你的作品');

    if (Array.isArray(value)) {
      if (value.some((item) => item.status === 'uploading')) {
        return Promise.reject('还有正在上传的作品，稍等一下');
      }
      if (value.some((item) => item.status === 'error')) {
        return Promise.reject('有上传失败的作品，请删除后重新上传');
      }
    }
    return Promise.resolve();
  };

  const validContact = (rule, value: any) => {
    if (!value) return Promise.reject('请选择你的联系方式');

    if (Array.isArray(value)) {
      if (!value.some((item) => item.checked && item.value)) {
        return Promise.reject('请勾选并填写你的联系方式');
      }
      const mobile = value.find((item) => item.key === 'mobiles');
      if (mobile.checked && !regMap.mobile.test(mobile.value)) {
        return Promise.reject('请填写正确的手机号');
      }
    }

    return Promise.resolve();
  };

  const handleUploadSuccess = async (_, file) => {
    if (isVideo(file.name)) {
      file.videoId = file?.response?.videoId;
      const response = await allGet({
        params: {
          version: 'pc1.0',
          mod: 'video',
          do: 'aliyun',
          action: 'upload',
          type: 'teacher',
          aid: file.aid || 0,
          filename: file.name,
          videoid: file.videoId,
        },
      });
      if (response.success && response?.data?.aid) {
        file.aid = response?.data?.aid;
      }
    }
  };
  const handlePreview = async (file) => {
    if (isVideo(file.name)) {
      if (!file.url) {
        const response = await allGet({
          params: {
            version: 'pc1.0',
            mod: 'video',
            do: 'aliyun',
            action: 'upload',
            type: 'teacher',
            aid: file.aid,
            videoid: file.videoId,
          },
        });
        if (!response?.data?.attachment) {
          return message.info('视频上传中，请稍后再试');
        }
        file.url = response?.data?.attachment;
      }
      VideoPlayerModal.showList({
        data: [
          {
            url: file.url,
          },
        ],
      });
    } else {
      VideoPlayerModal.showList({
        data: [
          {
            url: file.url,
          },
        ],
      });
    }
  };

  const handleRemove = async (file) => {
    if (file.status === 'error') return true;
    const reponse = await allGet({
      params: { mod: 'attachment', do: 'delete', aid: file.aid, version: 'pc1.0' },
    });
    if (reponse.success) {
      return true;
    }
    return false;
  };
  const initialValues = () => {
    const zp = config?.data?.pics?.map((item) => {
      const url = item.videoid ? item.attachment : item.pic;
      return {
        ...item,
        url,
        name: item.filename,
        uid: item.aid,
        videoId: item.videoid,
        status: 'done',
      };
    });
    return {
      zp,
    };
  };
  return (
    <div>
      <div className={styles.applytitle}>申请老师</div>
      {!loading && (
        <Form
          form={form}
          scrollToFirstError
          initialValues={initialValues()}
          className={styles.form}
          layout="vertical"
          name="basic"
          autoComplete="off"
          validateTrigger={false}
        >
          <Form.Item
            label="讲课项目："
            name="tag"
            rules={[{ required: true, message: '请选择讲课项目' }]}
          >
            <CheckTag data={categorys} />
          </Form.Item>

          <Form.Item label="你的作品：" name="zp" required rules={[{ validator: validUpload }]}>
            <DraggerUpload
              size={5}
              name="Filedata"
              action={apiUrl}
              payload={uploadPayload}
              onSuccess={handleUploadSuccess}
              onPreview={handlePreview}
              onRemove={handleRemove}
              getAliyunAuth={getAliyunAuth}
              refreshAliyunAuth={refreshAliyunAuth}
            />
          </Form.Item>
          <Form.Item label="联系方式：" name="lx" required rules={[{ validator: validContact }]}>
            <Contact />
          </Form.Item>
          <Form.Item label="性别：" name="sex" rules={[{ required: true, message: '请选择性别' }]}>
            <Gender />
          </Form.Item>
          <Form.Item
            label="工作经历："
            name="jl"
            rules={[{ required: true, message: '请填写工作经历' }]}
          >
            <Input.TextArea
              className={styles.textarea}
              placeholder="请输入"
              style={{ height: 140, backgroundColor: '#293E6B' }}
            />
          </Form.Item>
        </Form>
      )}
      <div className={styles.footer}>
        <div className={styles.submit} onClick={handleSubmit}>
          提交资料
        </div>
      </div>
    </div>
  );
};

const Applying = () => {
  return (
    <div className={styles.status}>
      <img
        loading="lazy"
        className={styles.icon}
        src={require('@/assets/pc/images/teachers/icon-applying.png')}
      />
      <div className={styles.des}>
        <p className={styles.subtitle1}>资料信息已经提交审核</p>
        <p className={styles.subtitle2}>审核通过后，会通过您填写的联系方式联系您</p>
      </div>
    </div>
  );
};
const Success = () => {
  return (
    <div className={styles.status}>
      <img
        loading="lazy"
        className={styles.icon}
        src={require('@/assets/pc/images/teachers/icon-applysuccess.png')}
      />
      <div className={styles.title}>审核成功</div>
      <div className={styles.button} onClick={() => history.push('/lecturer?index=5')}>
        填写合作信息
      </div>
    </div>
  );
};
const Fail = ({ onClick }) => {
  return (
    <div className={styles.status}>
      <img
        loading="lazy"
        className={styles.icon}
        src={require('@/assets/pc/images/teachers/icon-applyfail.png')}
      />
      <div className={styles.title}>审核失败</div>
      <div className={styles.button} onClick={onClick}>
        重新提交申请
      </div>
    </div>
  );
};

const Index = () => {
  const [loading, setLoading] = useState(true);
  const [config, setConfig] = useState<any>({});

  const init = async () => {
    setLoading(true);
    const response = await allGet({ params: { mod: 'teacher', do: 'add', version: 'pc1.0' } });
    setConfig(response);
    setLoading(false);
  };
  useEffect(() => {
    init();
  }, []);

  const handleSubmit = async (values) => {
    console.log(values);
    const value = {
      cid: values?.tag?.[0],
      resume: values?.jl,
      gender: values?.sex,
    };
    values?.lx?.forEach((item) => {
      if (item.checked === true) {
        value[item.key] = item.value;
      }
    });
    const response = await allGet({
      params: { mod: 'teacher', teachersubmit: 1, do: 'add', version: 'pc1.0', ...value },
    });
    if (response.success) {
      setStatus(2);
    }
  };

  /**
   * 申请老师状态
   * config?.data?.teacher
   * teacher === [] 是未提交过审核
   * teacher.status == -2 审核未通过
   * teacher.status == -1 审核中
   * teacher.status == 0 审核通过
   */

  const [status, setStatus] = useState<any>('');
  useEffect(() => {
    if (Array.isArray(config?.data?.teacher)) {
      setStatus(1);
    }
    if (config?.data?.teacher?.status == -1) {
      setStatus(2);
    }
    if (config?.data?.teacher?.status == 0) {
      setStatus(3);
    }
    if (config?.data?.teacher?.status == -2) {
      setStatus(4);
    }
  }, [config]);

  return (
    <div className={styles.page}>
      <div className={styles.main}>
        {/* <img
          loading="lazy"
          className={styles.titleimg}
          src={require('@/assets/pc/images/teachers/申请老师.png')}
          alt=""
        /> */}
        {/* <div className={styles.step}>
          <div className={classNames(styles.item, styles.actived)}>
            <div className={styles.icon}>
              <span className={styles.text}>1</span>
            </div>
            <div className={styles.text}>提交申请</div>
          </div>
          <i className={styles.line} />
          <div
            className={classNames(styles.item, {
              [styles.actived]: status !== undefined && status !== 1,
            })}
          >
            <div className={styles.icon}>
              <span className={styles.text}>2</span>
            </div>
            <div className={styles.text}>审核</div>
          </div>
        </div> */}
        {status === 1 && <ApplyForm config={config} onSubmit={handleSubmit} loading={loading} />}
        {status === 2 && <Applying />}
        {status === 3 && <Success />}
        {status === 4 && <Fail onClick={() => setStatus(1)} />}
      </div>
    </div>
  );
};

export default Index;
